<?php

/**
 * ECSHOP 商品分类
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liubo $
 * $Id: category.php 17217 2011-01-19 06:29:08Z liubo $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}
$act = !empty($_REQUEST['act'])?$_REQUEST['act']:'default';
$smarty->assign('act', $act);

/*领取鸡蛋白*/
if($act=='get_glair'){
    $smarty->assign('ajax', '1');
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $user_id = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';

    // $user_id = rand(1,100000);
    $time = time();
    $return=array('error'=>0,'message'=>'','content'=>'');
    if (empty($user_id)) {
        $return['error']=1;
        $return['message']="请登录后再领取";
        echo $json->encode($return);
        exit();
    }

    /*时间未到*/
    if ($time<1438956000) {
        $return['error']=8111;
        $return['message']="请登录后再领取";
        $smarty->assign('act', 'time');
        $return['content']=$smarty->fetch('get_glair.dwt');
        echo $json->encode($return);
        exit();
    }



    /*领取鸡蛋白程序*/
    $mem->set('glairStockOut','200');
    $mem->increment('counterA',1);//记录领取人数
    $is_get =$mem->get('userID'.$user_id);
    if (!empty($is_get)) {
        switch ($is_get) {
            case '1':
            $smarty->assign('act', 'over');
            $return['error']=8001;
            $return['message']="已领取";
            $return['content']=$smarty->fetch('get_glair.dwt');
            die($json->encode($return));
                break;
            case '2':
            $smarty->assign('act', 'fail');
            $return['error']=8003;
            $return['message']="发放完毕";
            $return['content']=$smarty->fetch('get_glair.dwt');
            die($json->encode($return));
                break;

            default:
                # code...
                break;
        }
    }else{
        $stock = $mem->decrement('glairStockOut',2);//减少库存
        if ($stock == 0) {
            $mem->set('userID'.$user_id,2);//标记已抢(抢不到的用户)
            $smarty->assign('act', 'fail');
            $return['error']=8003;
            $return['message']="发放完毕";
            $return['content']=$smarty->fetch('get_glair.dwt');
            die($json->encode($return));
        }else{
            $mem->set('userID'.$user_id,1);//标记已抢(抢到的用户)
            $mem->append('user_queue', ",$user_id");
            $smarty->assign('act', 'succeed');
            $return['error']=0;
            $return['message']="成功领取";
            $return['content']=$smarty->fetch('get_glair.dwt');
            die($json->encode($return));
        }
    }

}

/*重置数据测试*/
if ($act =='delete') {
    $mem->delete('userID12');
    $mem->delete('userID17895');
    $mem->delete('userID17888');
    $mem->delete('user_queue');
    $mem->delete('user_queue_old');
    $sql = "UPDATE ".$ecs->table('coupon')."SET user_id = 0 ";
    $db->query($sql);



}
if ($act == 'test') {
    $a=$mem->get('counterA');

    dump($a);

    # code...
}


/*释放队列*/
if ($act == 'release') {
    /*判断当前能否释放数据*/
    if (!$mem->get('is_release')) {
        $mem->add('is_release',"1");
        exit();
    }

    if (!empty($mem->get('is_release'))&&$mem->get('is_release') == 2) {
        echo 8888;
        echo '业务未结束';
       exit();
    }


    if (!empty($mem->get('is_release'))&&$mem->get('is_release') == 1) {
        $mem->set('is_release',"2");
    }

    /*获取队列数据*/
    $queue     = $mem->get('user_queue');
    $data      = explode(',',$queue);//队列中的所有数据
    $user_data = array_unique($data);
    $user_queue_old =$mem->get('user_queue_old');
    if (empty($user_queue_old)) {
        $post_num = 1;
        $post_data =$user_data;
    }else{
        $user_data_old   = explode(',',$user_queue_old);//已释放的数据
        $post_data=array_diff($user_data,$user_data_old);
    }
    $post_data = array_values($post_data);//需要处理业务的数据
    $number    = count($post_data)*2;
    /*批量领取包邮卷*/
    $time = time();
    $sql =  " SELECT coupon_id FROM ".$ecs->table('coupon').
            " WHERE get_start_time < $time AND get_end_time >$time AND user_id = 0 ".
            " LIMIT 0 , ".count($post_data);
    $coupon = $db->getAll($sql);
    foreach ($coupon as $key => $value) {
        $coupon_id[]=$value['coupon_id'];
    }
    unset($coupon);
    $coupon_list = implode( ',', $coupon_id );
    $sql =  " UPDATE ".$ecs->table('coupon').
            " SET user_id = CASE coupon_id ";
    foreach ($coupon_id as $key => $value) {
        $sql .=" WHEN '$value' THEN '$post_data[$key]'";
    }
    $sql.=" END WHERE coupon_id IN ($coupon_list)";
    $db->query($sql);
    unset($coupon_id);
    /* 查询礼包信息 */
    $sql = "SELECT name, original_price, parent_id, extension_code, price, is_sale FROM " . $GLOBALS['ecs']->table('activity') . " WHERE min_price = '87' AND extension_code = 'gift'";
    $info = $GLOBALS['db']->getRow($sql);
    $sql =  " INSERT INTO ".$ecs->table('cart').
            " ( user_id,goods_name, market_price, extension_code, extension_id,is_gift,area_id, add_time,goods_price,goods_number,parent_id)".
            " VALUES ";
    foreach ($post_data as $key => $value) {
        $sqls =$sqls ." , ('$value','".$info['name']."','".$info['original_price']."','gift','".$info['parent_id']."',1,'".time()."','$add_time','".$info['price']."','2','".$info['parent_id']."')";
    }
    $sql .=substr($sqls, 2);
    $db->query($sql);

    /* 修改礼包数量 */
    $sql = "UPDATE " . $GLOBALS['ecs']->table('activity_stock') . " SET valid_number = valid_number - $number,cart_number = (cart_number+$number) WHERE parent_id = '$info[parent_id]' AND area_id = '3'";
    $GLOBALS['db']->query($sql);
    /*标记已释放数据*/
    if (empty($post_num)) {
        $end_data =implode( ',', $post_data);
        $mem->append('user_queue_old',','.$end_data);
    }else{
        $user_queue =implode( ',', $user_data);
        $mem->set('user_queue_old',$user_queue);
    }

    $mem->set('is_release',"1");

}

    /*判断是否领取*/
    $user_id = !empty($_SESSION['user_id'])?$_SESSION['user_id']:'';
    if ($user_id) {
        $is_get =$mem->get('userID'.$user_id);
        $smarty->assign('is_get', $is_get);
        // 检测是否可以购买
        if (time() >= 1438956000) {
            if ($is_get == 2 || !empty($_SESSION["is_no_buy_glair_"]) || !is_buy_glair()) {
                // 不可购买的会员跳转至静态页面
                header("location: get_glair.html");
                exit;
            }
        }

    }
    $smarty->assign('back_url', "index.php");
    $smarty->assign('top_title', "试用鸡蛋白");
    $smarty->display('get_glair.dwt');


/**
 * 监测是否可以购买
 */
function is_buy_glair() {
    include_once(ROOT_PATH . 'includes/classCounter.php');
    $c = new classCounter();
    // 如果已经标记为不可购买，则直接返回false;
    if (!empty($_SESSION['is_no_buy_glair_']) || M()->get('is_no_buy_glair_' . $_SESSION['user_id'])) {
        $_SESSION['is_no_buy_glair_'] = 1;
        return false;
    } elseif (!empty($_SESSION['is_buy_glair_']) || M()->get('is_buy_glair_' . $_SESSION['user_id'])) {
        $_SESSION['is_buy_glair_'] = 1;
        return true;
    } else {
        // 查询分流是否满人，并标记是否可抢购
        if ($c->deCounter('set_sum_glair')) {
            M()->add('is_buy_glair_' . $_SESSION['user_id'], '1', 60);
            $_SESSION['is_buy_glair_'] = 1;
            return true;
        } else {
            M()->add('is_no_buy_glair_' . $_SESSION['user_id'], '1', 60);
            $_SESSION['is_no_buy_glair_'] = 1;
            return false;
        }
    }
}